package com.zy.cat.common.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.WebUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * 请求校验工具类
 * 
 * @author 32950745
 *
 */
@Slf4j
public class WeChatUtil {
    
    public static boolean sendTemplateMsg(String access_token,String touser,String template_id,String url,List<String> datas){
    	String requrl="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
    	Map<String, Object> params=new HashMap<String, Object>();
    	TreeMap<String, Object> data=new TreeMap<String, Object>();
    	params.put("touser", touser);
		params.put("template_id", template_id);
		if (!StringUtils.isEmpty(url)) {
			params.put("url", url);
		}
    
    	for (int i = 0; i < datas.size(); i++) {
    		Map<String, Object> data_item=new HashMap<String, Object>();
    		data_item.put("value", datas.get(i));
			data_item.put("color", "#173177");
			if(i==0) {
				data.put("first", data_item);
			}else if(i+1<datas.size()) {
				data.put("keyword"+i, data_item);
			}else {
				data_item.put("color", "#e91e63");
				data.put("remark", data_item);
			}
		}
    	params.put("data", data);
    	String content=JSON.toJSONString(params);
    	log.info("-params-->"+JSON.toJSONString(params,true));
    	String resultJson = null;
		try {
			resultJson=WebUtils.doPost(requrl, "application/json; encoding=utf-8", content.getBytes(), 9000, 9000, null, 0);
		} catch (IOException e) {
			e.printStackTrace();
		}
		log.info("sendTemplateMsg-->" + JSON.toJSONString(resultJson));
		JSONObject result = JSONObject.parseObject(resultJson);
		if (result != null) {
			if ("ok".equals(result.getString("errmsg"))) {
				return true;
			}
		}
		return false;
    }
    
    public static void main(String[] args) {
    	//access_token 通过 cacheService.getWechatAccessToken() 获取
    	String access_token="29_JU3eq9NMTSwjJS1pbQu9vJY5CsAK3ataXCHn4BLGFRlGZAy7MxJoNgf4A1-wr3_40xHP6jZPnv12fvKAy37hnatuXFxjyZzSbATnV2S7xtLbRa3E_01X-7Ygi7oXSZeAGALGN";
    	String touser="oo878wMnAjx5YDuGcWBFWLlRaIXc";
    	String template_id="O1vMlmSNJrKnMToxmE4XIhPqksfTQogaCqEJnkBDIuM";
    	String url="https://dev.adsteam.cn/index.htm";
    	List<String> datas=new ArrayList<String>();
    	datas.add("提现到账通知");//例子中第一条
    	datas.add("100元");//例子中第二条
    	datas.add("2019-10-10 10:10:10");
    	datas.add("备注信息");//例子中最后一条
    	sendTemplateMsg(access_token, touser, template_id, url, datas);
	}
    
}